/* eslint-disable eqeqeq */
'use strict'; // 声明js代码的严格模式

// 引入egg中的controller类
const Controller = require('egg').Controller;

const studentList = [{
  id: 1,
  name: '小明',
  fraction: 65,
},
{
  id: 2,
  name: '小桐桐',
  fraction: 85,
},
{
  id: 3,
  name: '小红',
  fraction: 95,
},
];

// 自定义controller用于继承egg的controller类
class StudentController extends Controller {
  // 定义查询方法，对应/student的get请求
  async index() {
    this.ctx.body = studentList;
  }

  // 定义添加方法，对应post请求
  async create() {
    const newStudent = this.ctx.request.body.newStudent;
    studentList.push(newStudent);
    this.ctx.body = studentList;
  }

  //   定义删除方法，对应delete请求
  async destroy() {
    const index = this.ctx.params.index;
    studentList.splice(index, 1);
    this.ctx.body = studentList;

  }


  // 定义修改方法，对应put请求
  async update() {
    const id = this.ctx.params.id;
    const upStudent = this.ctx.request.body.upStudent;
    for (let i = 0; i < studentList.length; i++) {
      if (id == studentList[i].id) {
        studentList[i] = upStudent;
        this.ctx.body = studentList;
      }
    }

  }

}

// 暴露定义的controller类
// eslint-disable-next-line eol-last
module.exports = StudentController;